﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DCT.AutoUpdate.Code.Log
{
    public static class LogExtension
    {
        public static string FormatException(Exception exception)
        {
            if (exception == null)
            {
                return "";
            }

            //{0} - 异常类型；{1} - message
            string msg = "{0}:{1}";
            return string.Format(msg, exception.GetType().Name, exception.Message);
        }

        public static string FormatExceptionStack(Exception exception)
        {
            if (exception == null)
            {
                return "";
            }

            //{0} - 异常类型；{1} - message；{2} - StackTrace
            string msg = "{0}:{1}:{2}";
            return string.Format(msg
                , exception.GetType().Name
                , exception.Message
                , exception.StackTrace);
        }

        public static string FormatFullException(Exception exception)
        {
            if (exception == null)
            {
                return "";
            }

            Dictionary<string, string> data = new Dictionary<string, string>();
            data["type"] = exception.GetType().Name;
            data["msg"] = exception.Message;
            data["source"] = exception.Source;
            data["stack"] = exception.StackTrace;

            return FormatDictory(data);
        }

        public static string FormatDictory<TValue>(Dictionary<string, TValue> data)
        {
            var formatdata = from item in data
                             select item.Key + "=" + CleanNewLine(StringUtility.ToString(item.Value));

            return string.Join("|", formatdata.ToArray());
        }

        public static string CleanNewLine(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ");
            }
            return str;
        }
    }
}
